<template>
  <div>
    <hr><br>
    <h1>这是 parent dom</h1>
    <button @click="sendMessage">传递消息</button>
    <iframe  ref="piframeRef"
        id="iframeId" :src="url" frameborder="1"  scrolling="auto"
       >
    </iframe>

    <hr><br>
  </div>
</template>

<script>

// import  ChildDom  from "./ChildDom";

export default {
  name:'ParentDom',
  components: {
    // ChildDom
  },
  data(){
    return {
      url:'http://127.0.0.1:5500/study_vue/demo01/demo-iframe-child-dom.html',
      iframeWin: {},
      verify:false,
      timer:null
    }
  },
  created(){

    // this.iframeWin = this.$refs.piframeRef.contentWindow
    // window.addEventListener('message', this.handleMessage)
    // this.$nextTick(() => {
    //   // 在外部 Vue 的 window 上添加 postMessage 的监听，并且绑定处理函数 handleMessage
    //   window.addEventListener('message', this.handleMessage)
    // })
    // this.sendMessage()
  },
  mounted(){

    this.iframeWin = this.$refs.piframeRef.contentWindow
    this.$nextTick(() => {
      // 在外部 Vue 的 window 上添加 postMessage 的监听，并且绑定处理函数 handleMessage
      window.addEventListener('message', this.handleMessage)
    })
    // this.sendMessage()
    this.setTimer()
  },
  destroyed () {
      // 注意移除监听！注意移除监听！注意移除监听！
      window.removeEventListener('message', this.handleMessage)
  }  ,
  methods:{
    sendMessage () {
      // 外部vue向iframe内部传数据
      this.iframeWin.postMessage({AuthorizationCode:'aaa',certificate:'bbb'}, '*')
    },
    handleMessage (event) {
      // 根据上面制定的结构来解析 iframe 内部发回来的数据
      console.log('handleMessage  event.data :' , event.data );

      if( event && event.data && event.data.verify  ){
        // 收到确认
        this.verify = true
        this.clearTimer()
      }
    },
    setTimer() {
        if(!this.timer) {
            this.timer = setInterval( () => {
              console.log('parent 发起消息');
                this.sendMessage()
            }, 1000)
        }
    },
    clearTimer(){
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>

<style>
.iframe {
    position: absolute;
    left: 10;
    right: 10;
    top: 10;
    bottom: 10;
    width: 800px ;
    height: 600px ;
    background: #fff;
    overflow-y: hidden;
}
</style>
